package com.itlxd.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itlxd.dto.DishDTO;
import com.itlxd.dto.DishFlavorDTO;
import com.itlxd.dto.PageDTO;
import com.itlxd.entity.Category;
import com.itlxd.entity.Dish;
import com.itlxd.entity.DishFlavor;
import com.itlxd.entity.SetmealDish;
import com.itlxd.exception.SqlOperationException;
import com.itlxd.global.ErrorCode;
import com.itlxd.global.SysConstants;
import com.itlxd.global.SysMessages;
import com.itlxd.mapper.DishFlavorMapper;
import com.itlxd.mapper.DishMapper;
import com.itlxd.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itlxd.vo.DishVO;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品管理 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2021-12-25
 */
@Service
public class DishServiceImpl implements IDishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private ISetmealDishService setmealDishService;
    @Autowired
    private IDishFlavorService dishFlavorService;
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Integer count(Long categoryId) {
        LambdaQueryWrapper<Dish> lambdaQuery = new LambdaQueryWrapper();
        lambdaQuery.eq(null != categoryId, Dish::getCategoryId, categoryId);
        return dishMapper.selectCount(lambdaQuery);
    }

    @Override
    public IPage<DishVO> listPageDishes(PageDTO pageDTO) {
        IPage<Dish> IPage = new Page<>(pageDTO.getPage(), pageDTO.getPageSize());
        //设置查询条件
        LambdaQueryWrapper<Dish> lambdaQuery = new LambdaQueryWrapper();
        lambdaQuery.like(!StringUtils.isEmpty(pageDTO.getName()), Dish::getName, pageDTO.getName())
                .eq(null != pageDTO.getStatus(), Dish::getStatus, pageDTO.getStatus());
        IPage<Dish> dishIPage = dishMapper.selectPage(IPage, lambdaQuery);
        //复制属性到DishVO当中
        IPage<DishVO> dishVOIPage = new Page<>();
        dishVOIPage.setTotal(dishIPage.getTotal());
        List<DishVO> dishVOs = dishIPage.getRecords().stream().map(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            //查询分类名称并赋值
            Category category = categoryService.getById(dish.getCategoryId());
            dishVO.setCategoryName(category.getName());
            return dishVO;
        }).collect(Collectors.toList());
        dishVOIPage.setRecords(dishVOs);

        return dishVOIPage;
    }

    @Override
    public DishVO getOneById(Long id) {
        DishVO dishVO = new DishVO();
        Dish dish = dishMapper.selectById(id);
        BeanUtils.copyProperties(dish, dishVO);
        List<DishFlavor> flavors = dishFlavorService.getByDishId(id);
        dishVO.setFlavors(flavors);

        return dishVO;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Integer saveDishAndDishFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        int row1 = dishMapper.insert(dish);
        int row2 = 0;
        if (null != dishDTO.getFlavors() && dishDTO.getFlavors().size() > SysConstants.NUM_ZERO) {
            List<DishFlavor> DishFlavorlist = dishDTO.getFlavors().stream().map(item -> {
                item.setDishId(dish.getId());
                return item;
            }).collect(Collectors.toList());
            row2 += dishFlavorService.insertBatch(DishFlavorlist);
        }

        //保存成功删除redis中保存的 根分类Id查询菜品列表
        redisTemplate.delete("dishVO:" + dish.getCategoryId() + "_" +dish.getStatus());

        // TODO 判断row2 == dishDTO.getFlavors().size()
        return row1 > 0 ? SysConstants.YES : SysConstants.NO;
    }

    @Override
    public Integer saveDish(Dish dish) {
        return dishMapper.insert(dish);
    }

    @Override
    public Integer updateBatchIds(Long[] ids, Integer status) {
        Dish dish = new Dish();
        Integer count = 0;

        for (Long id : ids) {
            dish.setId(id);
            dish.setStatus(status);
            dishMapper.updateById(dish);
            count++;
        }
        return count;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Integer updateDishWithDishFlavor(DishDTO dishDTO) {
        //查询原先数据的分类
        Long categoryId = dishMapper.selectById(dishDTO.getId()).getCategoryId();
        int row1 = dishMapper.updateById(dishDTO);
        //先删除所有口味然后遍历添加
        dishFlavorService.deleteBatchByDishId(new Long[]{dishDTO.getId()});
        List<DishFlavor> flavors = dishDTO.getFlavors();
        int row2 = 0;
        if (null != flavors && flavors.size() > SysConstants.NUM_ZERO) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishDTO.getId());
                dishFlavorService.insertFlavor(flavor);
                row2++;
            }
        }
        //删除redis中的数据
        redisTemplate.delete("dishVO:" + categoryId + "_1");
        redisTemplate.delete("dishVO:" + dishDTO.getCategoryId() + "_1");

        return row1 > SysConstants.NUM_ZERO ? SysConstants.NUM_ONE : SysConstants.NUM_ZERO;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Integer deleteBatchIds(Long[] ids) {
        int delNum = dishMapper.deleteBatchIds(Arrays.asList(ids));
        dishFlavorService.deleteBatchByDishId(ids);
        return delNum;
    }

    @Override
    public List<DishVO> listDishes(DishDTO dishDTO) {
        //查询redis当中是否有数据
        String redisKey = "dishVO:" + dishDTO.getCategoryId() + "_" + dishDTO.getStatus();
        Object obj = redisTemplate.opsForValue().get(redisKey);
        if (null != obj) {
            List list = JSON.parseObject(obj.toString(), List.class);
            return list;
        }

        //没有则查询数据库
        LambdaQueryWrapper<Dish> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.eq(null != dishDTO.getCategoryId(), Dish::getCategoryId, dishDTO.getCategoryId())
                .eq(null != dishDTO.getStatus(), Dish::getStatus, dishDTO.getStatus());
        List<Dish> list = dishMapper.selectList(lambdaQuery);

        List<DishVO> dishVoList = list.stream().map(item -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(item, dishVO);

            List<DishFlavor> flavors = dishFlavorService.getByDishId(dishVO.getId());
            dishVO.setFlavors(flavors);
            return dishVO;
        }).collect(Collectors.toList());

        //保存数据到redis
        redisTemplate.opsForValue().set(redisKey, JSON.toJSON(dishVoList));
        return dishVoList;
    }

    @Override
    public List<DishVO> listSetmealDishesByDishId(Long setmealId) {
        List<SetmealDish> setmealDishList = setmealDishService.listSetmealDishes(setmealId.toString());
        List<DishVO> result = setmealDishList.stream().map(setmealDish -> {
            DishVO dishVO = new DishVO();
            Dish dish = dishMapper.selectById(setmealDish.getDishId());
            BeanUtils.copyProperties(dish, dishVO);
            dishVO.setCopies(setmealDish.getCopies());
            return dishVO;
        }).collect(Collectors.toList());
        return result;
    }
}
